/*
 * Author: Honrun
 */
#include "stdio.h"
#include "stdint.h"
#include "DevicesList.h"

int8_t cListInit(ListType *ptypeList, int64_t lValue)
{
    if(ptypeList == NULL)
        return -1;

    ptypeList->pNext = ptypeList->pPrevious = ptypeList;
    ptypeList->value = lValue;

    return 0;
}

int8_t cListInsert(ListType *ptypeListHead, ListType *ptypeListNew)
{
    struct ListStruct *ptypeListNow = NULL;

    if((ptypeListHead == NULL) || (ptypeListNew == NULL))
        return -1;

    /* 插入到最后 */
    if(ptypeListNew->value >= LIST_VALUE_MAX)
    {
        return cListInsertEnd(ptypeListHead, ptypeListNew);
    }

    /* 找到排序插入的前一个位置 */
    for(ptypeListNow = ptypeListHead; ptypeListNow->pNext->value <= ptypeListNew->value; ptypeListNow = ptypeListNow->pNext);

    return cListInsertAfter(ptypeListNow, ptypeListNew);
}

int8_t cListInsertBefore(ListType *ptypeListBase, ListType *ptypeListNew)
{
    if((ptypeListBase == NULL) || (ptypeListNew == NULL))
        return -1;

    ptypeListNew->pPrevious         = ptypeListBase->pPrevious;
    ptypeListBase->pPrevious->pNext = ptypeListNew;
    ptypeListBase->pPrevious        = ptypeListNew;
    ptypeListNew->pNext             = ptypeListBase;

    return 0;
}

int8_t cListInsertAfter(ListType *ptypeListBase, ListType *ptypeListNew)
{
    if((ptypeListBase == NULL) || (ptypeListNew == NULL))
        return -1;

    ptypeListNew->pNext             = ptypeListBase->pNext;
    ptypeListBase->pNext->pPrevious = ptypeListNew;
    ptypeListBase->pNext            = ptypeListNew;
    ptypeListNew->pPrevious         = ptypeListBase;

    return 0;
}

int8_t cListInsertHead(ListType *ptypeListHead, ListType *ptypeListNew)
{
    return cListInsertAfter(ptypeListHead, ptypeListNew);
}

int8_t cListInsertEnd(ListType *ptypeListHead, ListType *ptypeListNew)
{
    return cListInsertBefore(ptypeListHead, ptypeListNew);
}

int8_t cListRemove(ListType *ptypeList)
{
    if(ptypeList == NULL)
        return -1;

    ptypeList->pPrevious->pNext = ptypeList->pNext;
    ptypeList->pNext->pPrevious = ptypeList->pPrevious;

    ptypeList->pNext = ptypeList->pPrevious = ptypeList;

    return 0;
}
